<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select v-model="query.params.storeId" clearable placeholder="请选择商铺编号">
              <el-option v-for="item in storeList" :key="item.value" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.goodsName" placeholder="商品名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" height="400" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="商铺商品编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="110">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImg">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.goodsName }}
          </template>
        </el-table-column>
        <el-table-column label="商品编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.goodsId }}
          </template>
        </el-table-column>
        <el-table-column label="商铺编号" width="110">
          <template slot-scope="scope">
            {{ scope.row.storeId }}
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作" width="100">
          <template slot-scope="scope">
            <el-link icon="el-icon-edit" style="cursor: pointer;" type="warning" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </el-link>
            <el-link v-if="!scope.row.isSet" icon="el-icon-delete" style="cursor: pointer;" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link v-if="!scope.row.isSet" icon="el-icon-sell" style="cursor: pointer;" type="primary" @click="handleEditBarcode(scope.$index, scope.row)">
              生成条码
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="storeGoodsRules" ref="StoreGoodsForm">
          <el-form-item label="商铺商品编号" hidden required prop="id">
            <el-input v-model="form.id" placeholder="商铺商品编号" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props" :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="商品编号" required prop="goodsId">
            <el-input v-model="form.goodsId" placeholder="商品编号" @focus="showGoods" suffix-icon="el-icon-goods" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品类型编号" prop="goodsTypeId">
            <el-input v-model="form.goodsTypeId" disabled placeholder="商品类型编号" suffix-icon="el-icon-goods" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品图片" required prop="goodsImg">
            <el-image style="width: 100px; height: 100px" v-bind:src="form.goodsImg">
            </el-image>
          </el-form-item>
          <el-form-item label="商品名称" required prop="goodsName">
            <el-input v-model="form.goodsName" placeholder="商品名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品单价" required prop="goodsPrice">
            <el-input v-model="form.goodsPrice" placeholder="商品单价" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品成本" required prop="costPrice">
            <el-input v-model="form.costPrice" placeholder="商品折扣价" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品折扣价" required prop="discountPrice">
            <el-input v-model="form.discountPrice" placeholder="商品折扣价" auto-complete="off" />
          </el-form-item>
          <el-form-item label="商品建议售价" required prop="suggestedRetailPrice">
            <el-input v-model="form.suggestedRetailPrice" placeholder="商品建议售价" auto-complete="off" />
          </el-form-item>
          <el-form-item label="父编号" hidden required prop="parentId">
            <el-input v-model="form.parentId" placeholder="父编号" auto-complete="off" />
          </el-form-item>
          <el-form-item label="所属商铺" required prop="storeId">
            <el-select v-model="form.storeId" style="width: 100%;" clearable placeholder="请选择所属商铺">
              <el-option v-for="item in storeList" :key="item.value" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" required prop="remark">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog :title="titleMap[dialogStatus]" width="50%" :visible.sync="dialogSelectGoodsFormVisible">

          <el-row>
          <el-col :span="6" style="margin: 0px 5px 0px 5px;" v-for="(goods, index) in goodsList" :key="goods">
            <el-card :body-style="{ padding: '0px' }" style="margin: 0px 5px 0px 5px;">
              <img :src="goods.goodsImg" class="image">
              <div style="padding: 14px; min-width:180px;">
                <div class="bottom clearfix">
                  <time class="time">{{ currentDate }}</time>
                  <!-- <el-button type="text" class="button">操作按钮</el-button> -->
                  <el-radio v-model="radio"  :label="goods.id">{{goods.goodsName}}</el-radio>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-pagination background layout="prev, pager, next" @current-change="handleQueryGoodsCurrentChange" :total="query.goods.total" :size-page="handleQueryGoodsSizeChange" :page-size="query.goods.pageSize">
          <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-pagination>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSelectGoodsFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleGetSelectedGoods">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 添加店铺商品时选择店铺的列表 -->
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormStoreVisible">
        <div class="block">
          <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column align="center" label="序号" width="95">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="所属组织" width="110">
              <template slot-scope="scope">
                {{ scope.row.organId }}
              </template>
            </el-table-column>
            <el-table-column label="组织路径" width="110">
              <template slot-scope="scope">
                {{ scope.row.organPath }}
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" width="110">
              <template slot-scope="scope">
                {{ scope.row.storeName }}
              </template>
            </el-table-column>
            <el-table-column label="纬度" width="110">
              <template slot-scope="scope">
                {{ scope.row.latitude }}
              </template>
            </el-table-column>
            <el-table-column label="经度" width="110">
              <template slot-scope="scope">
                {{ scope.row.longitude }}
              </template>
            </el-table-column>
            <el-table-column label="标注" width="110">
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" prop="created_at" label="操作">
              <template slot-scope="scope">
                <span class="el-tag el-tag--info el-tag--mini" style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
                  {{ scope.row.isSet?'保存':"修改" }}
                </span>
                <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
                  删除
                </span>
                <span v-else class="el-tag  el-tag--mini" style="cursor: pointer;" @click="pwdChange(scope.row,scope.$index,false)">
                  取消
                </span>
                <el-link v-has="'ORGAN_EDIT'" icon="el-icon-edit" type="warning" style="cursor: pointer;" @click="handleStoreAreaEdit(scope.$index, scope.row)">
                  块区管理
                </el-link>
                <el-divider v-has="'ORGAN_REMOVE'" direction="vertical"></el-divider>
                <el-link v-has="'ORGAN_EDIT'" icon="el-icon-edit" type="warning" style="cursor: pointer;" @click="handleStoreGoodsEdit(scope.$index, scope.row)">
                  添加商品
                </el-link>
                <el-divider v-has="'ORGAN_REMOVE'" direction="vertical"></el-divider>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-dialog>
    </div>

    <el-drawer title="生成条型码" :visible.sync="storeGoodsBarCodeEditVisable" :direction="direction" :before-close="handleClose" size="50%">
      <div class="demo-drawer__content" style="margin:0 16px 0 16px; height: 100%">
        <el-form :model="storeGoodsBarCode" :rules="storeGoodsBarcodeRules" :label-position="'left'" label-width="100px" ref="storeGoodsBarcodeForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="条形码"  prop="barCode" style="width: 100%;" required>
                <el-input v-model="storeGoodsBarCode.barCode" placeholder="条形码" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="条型码类型"  prop="barCodeType" style="width: 100%;" required>
                <el-select v-model="storeGoodsBarCode.barCodeType" placeholder="条型码类型" @change="createBarcode">
                  <el-option v-for="item in query.barCodeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所在块区"  prop="areaId" style="width: 100%;" required>
                <el-cascader v-model="storeGoodsBarCode.areaId" ref="areaTree" placeholder="所在块区" :props="areaProps" :options="areaOptions" @change="selectArea" collapse-tags clearable filterable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在货架"  prop="shelfId" style="width: 100%;" required>              
                <el-cascader v-model="storeGoodsBarCode.shelfId" ref="shelfTree" placeholder="所在货架" :props="shelfProps" :options="shelfOptions" @change="selectShelf" collapse-tags clearable filterable></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单价"  prop="price" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.price"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="进货价"  prop="originPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.originPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="折扣价"  prop="discountPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.discountPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建议售价"  prop="suggestedRetailPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.suggestedRetailPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="成本价"  prop="costPrice" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.costPrice" type="number"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存量"  prop="storeCount" style="width: 100%;" required>
                <el-input-number size="mini" v-model="storeGoodsBarCode.storeCount" type="number"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="条型码图">
                <img id="barcodeImg" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品图">
                <el-image style="width: 100px; height: 100px" :src="storeGoodsBarCode.url" :fit="'fit'"></el-image>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="storeGoodsBarCodeEditVisable = false">取 消</el-button>
          <el-button type="primary" @click="handleBarCodeEditSave">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getList, doDelete, doEdit } from '@/api/StoreGoods/'
import { getList as queryGoodsPagination } from '@/api/goods'
import { queryAreaOfStore } from '@/api/StoreArea/'
import { queryGoodsPriceBy as getGoodsPrice } from '@/api/goodsPrice'
import { getStoreList } from '@/api/Store/'
import { doEdit as saveStoreGoodsBarcode } from '@/api/storeGoodsBarcode'
import { queryGoodsShelfOfStore } from '@/api/GoodsShelf/'
import { getList as getOrganPager, querySubordinateOrgan, queryAssigneeOrgan } from '@/api/Organ'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary } from '@/utils/auth'
import JsBarcode from 'jsbarcode'

import localStorageUtil from '@/utils/localStorageUtil'


export default {
  data() {
    return {
      list: null,
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogSelectGoodsFormVisible: false,
      dialogFormStoreVisible: false,
      storeGoodsBarCodeEditVisable: false,
      goodsList: null,
      storeList: null,
      organTree: [],
      direction: 'rtl',
      form: {
        id: '',
        parentId: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        updateDate: '',
        remark: '',
        organId: '',
        organPath: '',
        isDeleted: '',
        storeId: '',
        goodsId: '',
        goodsImg: '',
        goodsName: '',
        goodsPrice: '',
        discountPrice: '',
        goodsTypeId: '',
        isHot: '',
        costPrice: '',
        suggestedRetailPrice: ''
      },
      storeGoodsBarCode: {
        id: '',
        storeGoodsId: '',
        tenantId: '',
        parentId: '',
        isDeleted: '',
        barCode: '',
        barCodeType: '',
        organId: '',
        organPath: '',
        createBy: '',
        createDate: '',
        updateBy: '',
        storeId: '',
        updateDate: '',
        remark: '',
        price: '',
        originPrice: '',
        discountPrice: '',
        suggestedRetailPrice: '',
        costPrice: '',
        areaName:''
      },
      goodsPrice: {},
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      radio: 0,
      storeOptions: [],
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      areaProps:{
        value: 'id',
        label: 'areaName',
        children: 'children',
        title: '块区',
        multiple: false,
        checkStrictly: true,
        emitPath: false
      },
      shelfProps:{
        value: 'id',
        label: 'shelfName',
        children: 'children',
        title: '货架',
        multiple: false,
        checkStrictly: true,
        emitPath: false
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      areaOptions: [{ id: '1', parentId: '2', areaName: '区块名称', children: [] }],
      shelfOptions: [{ id: '1', parentId: '2', shelfName: '货架名称', children: [] }],
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          id: '', //商铺商品编号
          parentId: '', //父编号
          createBy: '', //生成者  
          createDate: '', //生成时间
          updateBy: '', //更新时间,
          updateDate: '', //更新日期,
          emark: '', //备注,
          organId: '', //所属组织（商铺所属的组织）
          organPath: '', //组织路径
          isDeleted: '', //是否删除
          storeId: '', //商铺编号
          goodsId: '', //商品编号
          goodsImg: '' //商品图片

        },
        store: {
          addressId: '',
          createBy: '',
          createDate: '',
          enable: '',
          id: '',
          latitude: '',
          longitude: '',
          organId: '',
          organPath: '',
          remark: '',
          storeName: '',
          updateBy: '',
          updateDate: ''
        },
        storeArea: {
          addressId: '',
          areaName: '',
          createBy: '',
          createDate: '',
          enable: '',
          id: '',
          organId: '',
          organPath: '',
          parentId: '',
          remark: '',
          sorted: '',
          storeId: '',
          updateBy: '',
          updateDate: ''
        },
        goodsShelf: {
          id: '',
          organId: '',
          storeId: '',
          areaId: '',
          parentId: '',
          shelfName: '',
          sorted: '',
          enable: '',
          addressId: '',
          isDeleted: '',
          createBy: '',
          createDate: '',
          updateBy: '',
          updateDate: '',
          remark: ''
        },
        goods: {
          id: '',
          organId: '',
          organPath: '',
          organName: '',
          typeId: '',
          typePath: '',
          goodsName: '',
          supplierId: '',
          goodsImg: '',
          goodsDescribe: '',
          unit: '',
          unitValue: '',
          productionPlace: '',
          sys: '',
          isDeleted: '',
          quote: '',
          createBy: '',
          createDate: '',
          updateBy: '',
          updateDate: '',
          remark: '',
          assignee: {
            id: '',
            organPath: ''
          },
          total: 10,
          currentPage: 1,
          pageSize: 10
        },
        pager: {
          goods: {
            total: 10,
            currentPage: 1,
            pageSize: 10
          }
        },
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }],
        barCodeOptions: [{
          value: 'CODE39',
          label: 'code39'
        }, {
          value: 'CODE128',
          label: 'code128'
        },
        {
          value: 'EAN13',
          label: 'ean13'
        }],
        value: ''
      },
      storeGoodsBarcodeRules:{
        barCode:[
            { required: true, message: '请输入条码', trigger: 'change' }
          ],
        barCodeType:[ { required: true, message: '请选择条码类型', trigger: 'change' }],
        price :[{ required: true,  message: '请输入商品价格', trigger: 'change' }],
        originPrice: [{ required: true,  message: '请输入商品进货价', trigger: 'change' }],
        discountPrice:[{ required: true,  message: '请输入商品折扣价', trigger: 'change' }],
        suggestedRetailPrice:[{ required: true, message: '请输入商品建议价', trigger: 'change' }],
        costPrice:[{ required: true,  message: '请输入商品成本', trigger: 'change' }],
        storeCount:[{ required: true, message: '请填写库存量', trigger: 'change' }]
      },
      storeGoodsRules:{

      }
    }
  },
  created() {
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.handleGetStore();
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
          return;
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.parentId = ''
      this.form.createBy = getCurrentLoginUserId()
      this.form.createDate = ''
      this.form.updateBy = getCurrentLoginUserId()
      this.form.tenantId = getTenantId()
      this.form.updateDate = ''
      this.form.remark = ''
      this.form.organId = getOrganId()
      this.form.organPath = getOrganPath()
      this.form.organPath = ''
      this.form.isDeleted = ''
      this.form.storeId = ''
      this.form.goodsId = ''
      this.form.goodsImg = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)
      debugger
      this.form.id = row.id
      this.form.parentId = row.parentId
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.updateBy = getCurrentLoginUserId()
      this.form.updateDate = row.updateDate
      this.form.remark = row.remark
      this.form.organId = row.organId || getOrganId()
      this.form.organPath = row.organPath || getOrganPath()
      this.form.tenantId = row.tenantId || getTenantId()
      this.form.isDeleted = row.isDeleted
      this.form.storeId = row.storeId
      this.form.goodsId = row.goodsId
      this.form.goodsImg = row.goodsImg
      this.form.goodsName = row.goodsName
      this.form.goodsPrice = row.goodsPrice
      this.form.discountPrice = row.discountPrice

      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status == 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {

      doEdit(this.form).then(response => {
        debugger
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData();
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    showGoods() {
      this.dialogSelectGoodsFormVisible = true
      this.query.goods.assignee.id = getOrganId()
      queryGoodsPagination(this.query.goods, this.query.pager.goods.currentPage, this.query.pager.goods.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
          return;
        }
        this.query.pager.goods.total = data.totalCount
        this.query.pager.goods.pageSize = data.pageSize
        this.query.pager.goods.currentPage = data.currentPage
        this.goodsList = data.entities
        this.listLoading = false
      })
    },
    handleQueryGoodsCurrentChange(val) {
      this.query.pager.goods.currentPage = val
      this.showGoods()
    },
    handleQueryGoodsSizeChange(val) {
      this.query.pager.goods.currentPage = 1
      this.query.pager.goods.pageSize = val
      this.showGoods()
    },
    handleGetSelectedGoods() {
      let goods = null
      let goodsPrice = null
      for (let i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].id == this.radio) {
          goods = this.goodsList[i]
          this.listLoading = true
          getGoodsPrice({goodsId: goods.id, organId:getOrganId(), tenantId: getTenantId()}).then(response => {

            const result = response.data
            if (result.data) {
              goodsPrice = result.data
              this.form.goodsProductPlace = goods.productionPlace
              this.form.goodsPrice = goodsPrice.price
              this.form.costPrice = goodsPrice.costPrice
              this.form.discountPrice = goodsPrice.discountPrice
              this.form.suggestedRetailPrice = goodsPrice.typeId.suggestedRetailPrice
            }
            //this.form.goodsTypeId = goods.typeId
            this.form.goodsImg = goods.goodsImg
            this.listLoading = false
          })
          break;
        }
      }
      this.form.goodsId = goods.id
      this.form.goodsName = goods.goodsName
      this.form.goodsSpec = goods.goodsDescribe
      this.form.goodsTypeId = goods.goodsTypeId
      this.form.goodsImg = goods.goodsImg
      this.dialogSelectGoodsFormVisible = false
    },

    handleGetStore() {
      this.listLoading = true
      this.query.store.organPath = this.form.organPath ||  getOrganPath()
      this.query.store.tenantId = this.form.tenantId || getTenantId()
      getStoreList(this.query.store).then(response => {
        const gateway = response.data
        let data = gateway.data
        if(gateway.successful){
            this.storeList = data
        } else {
             this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false
      })
    },
    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      debugger
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function() {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleEditBarcode(index, row) {
      this.storeGoodsBarCodeEditVisable = true
      this.storeGoodsBarCode.id = ''
      this.storeGoodsBarCode.storeGoodsId = row.id
      this.storeGoodsBarCode.tenantId = row.tenantId || getTenantId()
      this.storeGoodsBarCode.parentId = ''
      this.storeGoodsBarCode.isDeleted = ''
      this.storeGoodsBarCode.barCode = ''
      this.storeGoodsBarCode.barCodeType = ''
      this.storeGoodsBarCode.organId = row.organId || getOrganId()
      this.storeGoodsBarCode.organPath = row.organPath || getOrganPath()
      this.storeGoodsBarCode.createBy = getCurrentLoginUserId()
      this.storeGoodsBarCode.createDate = ''
      this.storeGoodsBarCode.updateBy = ''
      this.storeGoodsBarCode.storeId = row.storeId
      this.storeGoodsBarCode.updateDate = ''
      this.storeGoodsBarCode.remark = ''
      this.storeGoodsBarCode.price = row.price
      this.storeGoodsBarCode.originPrice = ''
      this.storeGoodsBarCode.discountPrice = row.discountPrice
      this.storeGoodsBarCode.suggestedRetailPrice = row.suggestedRetailPrice
      this.storeGoodsBarCode.costPrice = row.costPrice

      //准备数据查询货区
      this.query.storeArea.storeId = row.storeId
      this.query.storeArea.organId = row.organId || getOrganId()
      this.query.storeArea.organPath = row.organPath || getOrganPath()
      this.query.storeArea.tenantId = row.tenantId || getTenantId()

      // 准备数据查货架
      this.query.goodsShelf.tenantId = row.tenantId  || getTenantId()
      this.query.goodsShelf.organId = row.organId || getOrganId()
      this.query.goodsShelf.storeId = row.storeId

      this.handleQueryAreaOfStore()
      this.handleQueryGoodsShelfOfArea()
    },
    createBarcode() {
      JsBarcode('#barcodeImg', this.storeGoodsBarCode.barCode, {
        format: this.storeGoodsBarCode.barCodeType, //选择要使用的条形码类型
        width: 1, //设置条之间的宽度
        height: 25, //高度
        displayValue: true, //是否在条形码下方显示文字
        textAlign: "center", //设置文本的水平对齐方式
        textPosition: "bottom", //设置文本的垂直位置
        textMargin: 5, //设置条形码和文本之间的间距
        fontSize: 15, //设置文本的大小
        background: "#eee", //设置条形码的背景
        lineColor: "#2196f3", //设置条和文本的颜色。
        margin: 15 //设置条形码周围的空白边距
      })
    },
    handleBarCodeEditSave() {
      this.$refs['storeGoodsBarcodeForm'].validate((valid) => {
          if (valid) {
            saveStoreGoodsBarcode(this.storeGoodsBarCode).then( (res) => {
              const data = res.data
              if (data.successful) {
                console.log(data)
              } else {
                this.$message({
                  type: 'info',
                  message: data.description || getSystemErrorCode(data.status)
                })
              }
              this.listLoading = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
      });
    },
    handleQueryAreaOfStore() {

      queryAreaOfStore(this.query.storeArea).then((res) => {
        const gateway = res.data
        if (gateway.successful) {
          this.areaOptions = handleBuildTreeDataStruct(gateway.data, 'id', 'parentId')
          this.listLoading = false
        } else {
          this.$message({
            type: 'info',
            message: gateway.description || getSystemErrorCode(gateway.status)
          })
          this.listLoading = false
        }
      })
    },
    handleQueryGoodsShelfOfArea() {
      this.listLoading = true
      this.query.goodsShelf.areaId = this.storeGoodsBarCode.areaId
      queryGoodsShelfOfStore(this.query.goodsShelf).then((res) => {
        const gateway = res.data
        if (gateway.successful) {
          this.shelfOptions = handleBuildTreeDataStruct(gateway.data, 'id', 'parentId')
          this.listLoading = false
        } else {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.listLoading = false

      })
    },
    selectArea(){
      this.storeGoodsBarCode.areaId = null
      let nodesInfo = this.$refs['areaTree'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.storeGoodsBarCode.areaId = nodesInfo[0].data.id
      }
      this.handleQueryGoodsShelfOfArea()

    },
    selectShelf(){
      let nodesInfo = this.$refs['shelfTree'].getCheckedNodes()
      if (nodesInfo[0]) {
        debugger
        this.storeGoodsBarCode.shelfId = nodesInfo[0].data.id
        this.storeGoodsBarCode.areaId = nodesInfo[0].data.areaId
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭【生成条型码】的抽屉吗？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
  }
}

</script>
